const express = require("express")
const router = express.Router()

router.use(logger)

router.get("/", (req, res) => {
    console.log(req.query.name)
    res.send("User List")
})

router.get("/new", (req, res) => {
    res.render("users/new", {name:"test"})
})

router.post("/", (req, res) => {
    const isValid = true
    if (isValid){
        users.push({name:req.body.name})
        res.redirect(`/users/${users.length -1}`)
    } else {
        console.log("err")
        res.render("users/new", {name:req.body.name})
    }
})

router.route('/:id')
    .get((req, res) => {
        console.log(req.user)
        res.send(`Create User id: ${req.params.id}`)
    })
    .put((req, res) => {
        res.send(`put User id: ${req.params.id}`)
    })
    .delete((req, res) => {
        res.send(`delete User id: ${req.params.id}`)
    })

const users = [{ name: "AAA" }, { name: "BBB" }]
router.param("id", (req, res, next, id) => {
    console.log(id)
    req.user = users[id]
    next()
})

function logger(req, res, next){
    console.log('路由内中间件')
    next()
}

module.exports = router